package service

import (
	"github.com/cihub/seelog"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"time"
)

func StartTimerTask() {
	timerClearCacheAt24()
	timerTaskPerHour()
}

// 凌晨0点开始清理缓存
func timerClearCacheAt24() {
	go func() {
		for {
			now := time.Now()
			next := now.Add(time.Hour * 24)
			next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
			timer := time.NewTimer(next.Sub(now))
			<-timer.C

			seelog.Infof("清除今日验证码的发送次数记录, count=%d", dao.GetRedisCli().Del(constant.CacheKeyVerifyCodeSendCountMap).Val())
			seelog.Infof("自动确认收货超过2天未完成的订单")
			dao.GetDB().Table(entity.TableNameOrderInfo).
				Where("(order_status=? or order_status=?) and create_time<?", constant.OrderStatusWaitTake, constant.OrderStatusWaitSend, time.Now().Unix()*1000-3600*24*2).
				UpdateColumn("order_status", constant.OrderStatusFinished)
		}
	}()
}

func timerTaskPerHour() {
	go func() {
		for {
			<-time.Tick(time.Hour)

			seelog.Debugf("删除一小时内未付款的订单")
			dao.GetDB().Table(entity.TableNameOrderInfo).
				Where("order_status=? and create_time<?", constant.OrderStatusNotPay, time.Now().Unix()*1000-3600).
				Delete(nil)
		}
	}()
}
